/**
 *   Copyright 2013 Royce Remulla
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package cjcast.common;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;


/**
 * Array Utilities.
 */
public final class ArrayUtil {


    /** Utility class. */
    private ArrayUtil() {}


    /**
     * @param primitiveArray primitive type array.
     */
    public static Object[] toObjectArray(final Object primitiveArray)
    {
        if (primitiveArray == null) {
            return null; //NOPMD: Return early.
        }

        assert primitiveArray.getClass().isArray() : "Parameter must be an array.";

        final int length = Array.getLength(primitiveArray);
        final List<Object> objectList = new ArrayList<Object>();
        for (int i = 0; i < length; i++) {
            objectList.add(Array.get(primitiveArray, i));
        }
        return objectList.toArray(new Object[length]);
    }

    /**
     * Convert reference type array to primitive typed array. Must be casted by
     * client because generics are not applicable to primitive types.
     * 
     * @param klass primitive type class.
     * @param arr Object typed array.
     * @param <T> primitive type.
     */
    @SuppressWarnings({ "PMD.DataflowAnomalyAnalysis" })
    public static <T> Object toPrimitiveArray(final Class<T> klass,
            final Object arr)
    {
        assert klass != null;
        assert arr.getClass().isArray() : "Parameter must be an array.";

        if (arr == null) {
            return null; //NOPMD: Return early.
        }

        final int length = Array.getLength(arr);
        final Object retval = Array.newInstance(klass, length);

        for (int i = 0; i < length; i++) {
            final Object arrElement = Array.get(arr, i);
            if (arrElement != null) {
                Array.set(retval, i, arrElement);
            }
        }
        return retval;
    }

}
